<template>
  <!-- 账号密码登录页面 -->
  <Vcode :show="isShow" @success="success" @close="close" @fail="fail"></Vcode>
  <div>
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <!-- <el-form-item prop="namea">
        <div class="flex labelClass margin-bottom">
          <img src="../assets/images/login/qiye.png" alt="" />
          <el-input
            disabled
            :input-style="{
              boxShadow: 'none',
            }"
            v-model="loginForm.namea"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="工厂编号"
          />
        </div>
      </el-form-item> -->
      <el-form-item prop="username">
        <div class="flex labelClass margin-bottom">
          <img src="../assets/images/login/user.png" alt="" />
          <el-input :input-style="{
              boxShadow: 'none',
            }" v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号" />
        </div>
      </el-form-item>
      <el-form-item prop="password">
        <div class="flex labelClass">
          <img src="../assets/images/login/wordpass.png" alt="" />
          <el-input :input-style="{
              boxShadow: 'none',
            }" v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
            @keyup.enter="handleLogin" />
        </div>
      </el-form-item>
      <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px">记住密码</el-checkbox> -->
      <el-form-item style="width: 100%; margin-top: 55px">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="display: flex; align-items: center" v-if="!register">
          <!-- <router-link type="primary" class="link-type" :to="'/register'"
            >立即注册</router-link
          >
          <el-divider direction="vertical" /> -->

          <!-- <router-link type="primary" class="link-type" :to="'/forgotPwd'"
            >忘记密码</router-link
          >
          <el-divider direction="vertical" /> -->
          <AppQcode />
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
  import { getIsRegistrationAPI } from "@/api/system/user.js";
  import Vcode from "vue3-puzzle-vcode";
  import { getCodeImg } from "@/api/login";
  import Cookies from "js-cookie";
  import { encrypt, decrypt } from "@/utils/jsencrypt";
  import useUserStore from "@/store/modules/user";
  import AppQcode from "./appQcode.vue";
  const to = () => {
    window.open("https://www.pureut.com/");
  };

  const audio = ref(null);
  const userStore = useUserStore();
  const router = useRouter();
  const { proxy } = getCurrentInstance();
  const isShow = ref(false);
  const loginForm = ref({
    username: "",
    password: "",
  });

  const loginRules = {
    username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
    password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
    // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
  };

  const codeUrl = ref("");
  const loading = ref(false);
  // 验证码开关
  const captchaEnabled = ref(true);
  // 注册开关
  const register = ref(false);
  const redirect = ref(undefined);

  // 账号密码登录校验
  async function handleLogin() {
    const valid = await proxy.$refs.loginRef.validate();

    if (!valid) return;
    try {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), {
          expires: 30,
        });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }

      userStore.login(loginForm.value).then(() => {
        router.push({ path: redirect.value || "/" });
      });
    } catch {
    } finally {
      loading.value = false;
    }

    // isShow.value = true
  }

  function getCookie() {
    const username = Cookies.get("username");
    const password = Cookies.get("password");
    const rememberMe = Cookies.get("rememberMe");
    loginForm.value = {
      username: username === undefined ? loginForm.value.username : username,
      password:
        password === undefined ? loginForm.value.password : decrypt(password),
      rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
    };
  }

  getCookie();

  // 用户通过了验证
  const success = async (msg) => {
    isShow.value = false;
    loading.value = true;
    const res = await getIsRegistrationAPI(loginForm.value);
    if (res?.data && res.data.isStatus != "2")
      return router.push(`/InitializeForm?id=${loginForm.value.username}`);
    userStore
      .login(loginForm.value)
      .then(() => {
        router.push({ path: redirect.value || "/" });
      })
      .catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          // getCode();
        }
      })
      .finally(() => {
        loading.value = true;
      });
  };
  // 用户点击遮罩层，应该关闭模态框
  const close = () => {
    isShow.value = false;
  };
  // 用户验证失败
  const fail = () => {
    console.log("失败了");
    loading.value = false;
  };
</script>

<style lang="scss" scoped>
  .labelClass {
    width: 100%;
    border-bottom: 0.0625rem solid #c8c8c8;
    margin-bottom: 1.625rem;
  }

  .margin-bottom {
    margin-bottom: 2.75rem;
  }

  img {
    width: 1.75rem;
    height: 1.75rem;
  }

  .link-type {
    color: #4193fd;
    font-weight: 700;
  }
</style>